﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace Data.AID
{
    public class Historico
    {
        public int IdHistorico { get; set; }
        public int IdFormulario { get; set; }
        public string Origem { get; set; }
        public string Destino { get; set; }
        public int AcaoId { get; set; }
        public string AcaoDesc { get; set; }
        public string CriadoPor { get; set; }
        public DateTime Criado { get; set; }
        
    }
    
    public class HistoricoDAO
    {
        private SPSite Site = SPContext.Current.Site;
        private SPWeb Web = SPContext.Current.Web;

        public void CreateHistory(Historico history)
        {
            using (SPSite eSite = new SPSite(Site.ID))
            {
                using (SPWeb eWeb = eSite.OpenWeb(Web.ID))
                {
                    SPListItemCollection listItems = eWeb.Lists["Historico"].Items;
                    SPListItem item = listItems.Add();

                    item["Origem"] = history.Origem;
                    item["Destino"] = history.Destino;
                    item["lkpAcao"] = history.AcaoId;
                    item["IdForm"] = history.IdFormulario;

                    item.Update();
                }
            }
        }
        public List<Historico> GetAllHistories()
        {
            using (SPSite eSite = new SPSite(Site.ID))
            {
                using (SPWeb eWeb = eSite.OpenWeb(Web.ID))
                {
                    return eWeb.Lists["Historico"].Items.Cast<SPListItem>()
                        .Select(p => new Historico
                        {
                            IdHistorico = Convert.ToInt32(p["ID"]),
                            Origem = p["Origem"].ToString(),
                            Destino = p["Destino"].ToString(),
                            AcaoId = new SPFieldLookupValue(p["lkpAcao"].ToString()).LookupId,
                            AcaoDesc = new SPFieldLookupValue(p["lkpAcao"].ToString()).LookupValue,
                            IdFormulario = new SPFieldLookupValue(p["IdForm"].ToString()).LookupId,
                            CriadoPor = p["Criado por"].ToString(),
                            Criado = Convert.ToDateTime(p["Criado"])
                        }).ToList();
                }
            }
        }
        public List<Historico> GetHistoryByForm(int form)
        {
            return GetAllHistories().Where(p => p.IdFormulario == form).OrderByDescending(p => p.Criado.Date).ToList();
        }

    }
}
